import $ from 'jquery';
import {
  NOTE_SWITCH,
  NOTE_ADD,
  NOTE_SYNC,
  NOTE_LIST_RESET,
  NOTE_REMOVE,
  NOTE_UPDATING,
  NOTE_UPDATED
} from './actionTypes';

let _updateNoteJob = undefined;

export function switchNote(note) {
  return {
    type: NOTE_SWITCH,
    note: note
  }
}

export function addNote(note) {
  return {
    type: NOTE_ADD,
    note: note
  }
}

export function syncNote(note) {
  return {
    type: NOTE_SYNC,
    note: note
  }
}

export function resetNoteList(notes) {
  return {
    type: NOTE_LIST_RESET,
    items: notes
  }
}

export function fetchNoteList(selector) {
  return function (dispatch) {
    $.get("/api/note", selector).done(({data})=> {
      dispatch(resetNoteList(data))
    });
  }
}

export function createNote(bookId, title, content, ext='sim') {
  return function (dispatch) {
    dispatch({type: NOTE_UPDATING});
    $.ajax({
      'url': '/api/note',
      'method': 'POST',
      'data': {bookId, title, content, ext}
    }).done(function ({data}) {
      dispatch(addNote(data));
      dispatch(switchNote(data));
    });
  }
}

export function updateNote(_id, title, content) {
  return function (dispatch) {
    if (!_id) return;
    dispatch(syncNote({_id, title, content}));
    dispatch({type: NOTE_UPDATING});
    if (_updateNoteJob) clearTimeout(_updateNoteJob);
    _updateNoteJob = setTimeout(function (title, content) {
      return function () {
        $.ajax({
          'url': `/api/note/${_id}`,
          'method': 'PUT',
          'data': {title, content}
        }).done(function () {
          dispatch({type: NOTE_UPDATED});
          _updateNoteJob = null;
        });
      }
    }(title, content), 500);
  }
}


export function removeNote(note) {
  return function (dispatch) {
    $.ajax({
      'url': `/api/note/${note._id}`,
      'dataType': 'json',
      'contentType': 'application/json',
      'method': 'DELETE',
      'data': JSON.stringify({'force': false})
    }).done(function () {
      dispatch({
        type: NOTE_REMOVE,
        note: note
      });
    });
  };
}

export function dropNote(note) {
  return function (dispatch) {
    $.ajax({
      'url': `/api/note/${note._id}`,
      'dataType': 'json',
      'contentType': 'application/json',
      'method': 'DELETE',
      'data': JSON.stringify({'force': true})
    }).done(function () {
      dispatch({
        type: NOTE_REMOVE,
        note: note
      });
    });
  }
}

export function switchNoteFromRemote(_id) {
  return function (dispatch) {
    $.ajax({
      'url': `/api/note/${_id}`,
      'method': 'GET'
    }).done(function ({data}) {
      dispatch(switchNote(data));
    });
  };
}